import pygame
from .menu import Button

class GameUI:
    """游戏内UI类"""
    
    def __init__(self, screen_width, screen_height):
        """
        初始化游戏UI
        
        参数:
            screen_width: 屏幕宽度
            screen_height: 屏幕高度
        """
        self.screen_width = screen_width
        self.screen_height = screen_height
        
        # 创建游戏内按钮
        self.pause_button = Button(screen_width - 120, 20, 100, 40, "暂停", (100, 100, 150), (120, 120, 180))
        self.shuffle_button = Button(screen_width - 120, 70, 100, 40, "重排", (150, 100, 100), (180, 120, 120))
        
    def update(self, mouse_pos):
        """
        更新UI状态
        
        参数:
            mouse_pos: 鼠标位置(x, y)
        """
        self.pause_button.update(mouse_pos)
        self.shuffle_button.update(mouse_pos)
        
    def draw(self, screen, game_logic):
        """
        绘制游戏UI
        
        参数:
            screen: pygame的Surface对象
            game_logic: 游戏逻辑对象，用于获取游戏状态
        """
        # 绘制按钮
        self.pause_button.draw(screen)
        self.shuffle_button.draw(screen)
        
        # 绘制游戏信息
        self._draw_game_info(screen, game_logic)
        
    def _draw_game_info(self, screen, game_logic):
        """绘制游戏信息"""
        font = pygame.font.SysFont('SimHei', 28)
        
        # 绘制分数
        score_text = font.render(f"分数: {game_logic.board.score}/{game_logic.target_score}", True, (255, 255, 255))
        screen.blit(score_text, (20, 20))
        
        # 绘制时间
        minutes = int(game_logic.time_left) // 60
        seconds = int(game_logic.time_left) % 60
        time_text = font.render(f"时间: {minutes:02d}:{seconds:02d}", True, (255, 255, 255))
        screen.blit(time_text, (20, 60))
        
        # 绘制关卡信息
        level_text = font.render(f"关卡: {game_logic.current_level}", True, (255, 255, 255))
        screen.blit(level_text, (20, 100))
        
        # 绘制操作次数
        moves_text = font.render(f"移动次数: {game_logic.board.moves}", True, (255, 255, 255))
        screen.blit(moves_text, (20, 140))
        
    def handle_event(self, event, game_logic):
        """
        处理UI事件
        
        参数:
            event: pygame事件对象
            game_logic: 游戏逻辑对象
            
        返回值:
            str: 'pause', 'shuffle' 或 None
        """
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_pos = pygame.mouse.get_pos()
            
            # 处理暂停按钮点击
            if self.pause_button.rect.collidepoint(mouse_pos):
                return 'pause'
                
            # 处理重排按钮点击
            if self.shuffle_button.rect.collidepoint(mouse_pos):
                return 'shuffle'
                
        return None

class LoginUI:
    """登录界面类"""
    
    def __init__(self, screen_width, screen_height):
        """
        初始化登录界面
        
        参数:
            screen_width: 屏幕宽度
            screen_height: 屏幕高度
        """
        self.screen_width = screen_width
        self.screen_height = screen_height
        
        # 创建标题
        self.title = "用户登录"
        self.title_font = pygame.font.SysFont('SimHei', 48)
        
        # 创建输入框
        input_width = 300
        input_height = 40
        input_x = (screen_width - input_width) // 2
        
        self.username_input = InputBox(input_x, screen_height // 3, input_width, input_height, "用户名")
        self.password_input = InputBox(input_x, screen_height // 3 + 60, input_width, input_height, "密码", password=True)
        
        # 创建按钮
        button_width = 120
        button_height = 40
        button_y = screen_height // 3 + 140
        
        self.login_button = Button((screen_width - button_width * 2 - 30) // 2, button_y, button_width, button_height, "登录", (50, 150, 50), (70, 180, 70))
        self.register_button = Button((screen_width + 30) // 2, button_y, button_width, button_height, "注册", (50, 100, 150), (70, 120, 180))
        self.back_button = Button(50, 50, 100, 40, "返回", (100, 100, 100), (130, 130, 130))
        
        # 状态信息
        self.status_message = ""
        self.status_color = (255, 0, 0)  # 默认红色（错误）
        
    def update(self, mouse_pos):
        """更新UI状态"""
        self.username_input.update()
        self.password_input.update()
        self.login_button.update(mouse_pos)
        self.register_button.update(mouse_pos)
        self.back_button.update(mouse_pos)
        
    def draw(self, screen):
        """绘制登录界面"""
        # 绘制背景
        screen.fill((30, 30, 50))
        
        # 绘制标题
        title_surf = self.title_font.render(self.title, True, (255, 255, 255))
        title_rect = title_surf.get_rect(center=(self.screen_width // 2, self.screen_height // 6))
        screen.blit(title_surf, title_rect)
        
        # 绘制输入框
        self.username_input.draw(screen)
        self.password_input.draw(screen)
        
        # 绘制按钮
        self.login_button.draw(screen)
        self.register_button.draw(screen)
        self.back_button.draw(screen)
        
        # 绘制状态信息
        if self.status_message:
            font = pygame.font.SysFont('SimHei', 24)
            text = font.render(self.status_message, True, self.status_color)
            text_rect = text.get_rect(center=(self.screen_width // 2, self.screen_height // 3 + 200))
            screen.blit(text, text_rect)
            
    def handle_event(self, event):
        """
        处理UI事件
        
        参数:
            event: pygame事件对象
            
        返回值:
            tuple: (str, dict) - ('login', {'username': str, 'password': str}), 
                              ('register', {'username': str, 'password': str}),
                              ('back', None) 或 (None, None)
        """
        # 处理输入框事件
        self.username_input.handle_event(event)
        self.password_input.handle_event(event)
        
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            mouse_pos = pygame.mouse.get_pos()
            
            # 处理登录按钮点击
            if self.login_button.rect.collidepoint(mouse_pos):
                username = self.username_input.text.strip()
                password = self.password_input.text.strip()
                
                if not username:
                    self.status_message = "请输入用户名"
                    return (None, None)
                    
                if not password:
                    self.status_message = "请输入密码"
                    return (None, None)
                    
                return ('login', {'username': username, 'password': password})
                
            # 处理注册按钮点击
            if self.register_button.rect.collidepoint(mouse_pos):
                username = self.username_input.text.strip()
                password = self.password_input.text.strip()
                
                if not username:
                    self.status_message = "请输入用户名"
                    return (None, None)
                    
                if not password:
                    self.status_message = "请输入密码"
                    return (None, None)
                    
                if len(username) < 3:
                    self.status_message = "用户名至少需要3个字符"
                    return (None, None)
                    
                if len(password) < 6:
                    self.status_message = "密码至少需要6个字符"
                    return (None, None)
                    
                return ('register', {'username': username, 'password': password})
                
            # 处理返回按钮点击
            if self.back_button.rect.collidepoint(mouse_pos):
                return ('back', None)
                
        return (None, None)
        
    def set_status(self, message, is_error=True):
        """
        设置状态信息
        
        参数:
            message: 状态消息
            is_error: 是否为错误信息
        """
        self.status_message = message
        self.status_color = (255, 0, 0) if is_error else (0, 255, 0)

class InputBox:
    """文本输入框类"""
    
    def __init__(self, x, y, width, height, placeholder="", text="", password=False):
        """
        初始化输入框
        
        参数:
            x, y: 输入框左上角坐标
            width, height: 输入框宽高
            placeholder: 占位文本
            text: 初始文本
            password: 是否为密码输入框
        """
        self.rect = pygame.Rect(x, y, width, height)
        self.placeholder = placeholder
        self.text = text
        self.password = password
        self.active = False
        self.font = pygame.font.SysFont('SimHei', 24)
        
        # 颜色
        self.inactive_color = (100, 100, 100)
        self.active_color = (150, 150, 200)
        self.text_color = (255, 255, 255)
        self.placeholder_color = (150, 150, 150)
        
        # 光标
        self.cursor_visible = True
        self.cursor_timer = 0
        
    def handle_event(self, event):
        """
        处理输入框事件
        
        参数:
            event: pygame事件对象
            
        返回值:
            bool: 输入框是否发生变化
        """
        if event.type == pygame.MOUSEBUTTONDOWN:
            # 切换输入框激活状态
            self.active = self.rect.collidepoint(event.pos)
            return False
            
        if self.active and event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                self.active = False
                return True
                
            elif event.key == pygame.K_BACKSPACE:
                self.text = self.text[:-1]
                return True
                
            else:
                # 只接受可打印字符
                if event.unicode.isprintable():
                    self.text += event.unicode
                    return True
                    
        return False
        
    def update(self):
        """更新输入框状态"""
        # 更新光标闪烁
        if pygame.time.get_ticks() - self.cursor_timer > 500:
            self.cursor_visible = not self.cursor_visible
            self.cursor_timer = pygame.time.get_ticks()
            
    def draw(self, screen):
        """绘制输入框"""
        # 绘制输入框背景
        color = self.active_color if self.active else self.inactive_color
        pygame.draw.rect(screen, color, self.rect, border_radius=5)
        pygame.draw.rect(screen, (200, 200, 200), self.rect, 1, border_radius=5)
        
        # 绘制文本或占位符
        if self.text:
            if self.password:
                display_text = "*" * len(self.text)
            else:
                display_text = self.text
                
            text_surf = self.font.render(display_text, True, self.text_color)
            text_rect = text_surf.get_rect(midleft=(self.rect.left + 10, self.rect.centery))
            
            # 裁剪文本，确保不超出输入框
            if text_rect.width > self.rect.width - 20:
                text_rect.width = self.rect.width - 20
                text_rect.x = self.rect.left + 10
                
            screen.blit(text_surf, text_rect)
            
            # 绘制光标
            if self.active and self.cursor_visible:
                cursor_x = text_rect.right
                if cursor_x < self.rect.right - 10:
                    pygame.draw.line(screen, self.text_color, 
                                    (cursor_x, self.rect.top + 10), 
                                    (cursor_x, self.rect.bottom - 10), 2)
        else:
            # 绘制占位符
            placeholder_surf = self.font.render(self.placeholder, True, self.placeholder_color)
            screen.blit(placeholder_surf, (self.rect.left + 10, self.rect.top + (self.rect.height - placeholder_surf.get_height()) // 2)) 